package com.lzj.server.repository.mapper;

import com.lzj.server.admin.entity.Permission;
import com.lzj.server.admin.entity.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface AdminMapper {
    /**
     * 添加角色
     */
    @Insert("INSERT INTO sys_role (role_name, role_code, description, create_time, update_time)\n" +
            "VALUES (#{r.roleName}, #{r.roleCode}, #{r.description}, NOW(), NOW())")
    void addRole(@Param("r") Role role);

    /**
     * 添加权限
     */
    @Insert("INSERT INTO sys_permission (permission_name, permission_code,description, create_time, update_time)\n" +
            "VALUES (#{p.permissionName}, #{p.permissionCode}, #{p.description}, NOW(), NOW())")
    void addPermission(@Param("p") Permission permission);

    /**
     * 根据用户ID查询角色
     */
    @Select("SELECT role_code FROM sys_role WHERE id IN (SELECT role_id FROM sys_user_role WHERE user_id = #{userId})")
    List<String> selectRole(@Param("userId") Long userId);

    /**
     * 根据用户ID查询权限
     */
    @Select("""
            SELECT sp.permission_code
            FROM  user_info u
                     INNER JOIN sys_user_role sur ON u.id = sur.user_id
                     INNER JOIN sys_role_permission srp ON sur.role_id = srp.role_id
                     INNER JOIN sys_permission sp ON srp.permission_id = sp.id
            WHERE u.id = #{userId};
            """)
    List<String> selectPermission(Long userId);

    /**
     * 查询所有权限
     */
    @Select("SELECT * from sys_role WHERE is_deleted = 0 ORDER BY id")
    List<Permission> getPermissionList();

    /**
     * 查询所有角色
     */
    @Select("SELECT * from sys_permission WHERE is_deleted = 0 ORDER BY id")
    List<Role> getRoleList();

    /**
     * 删除角色
     */
    @Update("UPDATE sys_role SET is_deleted = 1,update_time = now() WHERE id = #{id}")
    void deleteRoleById(@Param("id") Long id);

    /**
     * 删除权限
     */
    @Update("UPDATE sys_permission SET is_deleted = 1,update_time= now() WHERE id = #{id}")
    void deletePermissionById(@Param("id") Long id);

    /**
     * 删除角色权限关系
     */
    @Delete("DELETE FROM sys_role_permission WHERE role_id = #{roleId}")
    void deleteRolePermission(Long roleId);

    /**
     * 配置权限
     */
    @Insert("INSERT INTO sys_role_permission (role_id, permission_id) VALUES (#{id}, #{p})")
    void configPermission(@Param("p") Long permissionId, @Param("id") Long roleId);

    /**
     * 删除用户角色关联
     */
    @Delete("DELETE FROM sys_user_role WHERE user_id = #{userId}")
    void deleteUserRole(Long userId);

    /**
     * 配置用户角色关联
     */
    @Insert("INSERT INTO sys_user_role (user_id, role_id) VALUES (#{userId}, #{roleId})")
    void configUserRole(Long userId, Long roleId);

    /**
     * 根据角色编号查询角色ID
     */
    @Select("SELECT id FROM sys_role WHERE role_code = #{roleCode} ORDER BY id LIMIT 1")
    Long getRoleIdByCode(String roleCode);
}
